﻿using RMS.Common;
using RMS.EF.Model;
using RMS.EF.Model.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace RMS.BLL
{
    public class ConnectTestBll
    {
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public CommonOutPutVm SaveAddUserInfo(Demo_User user)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                using (var dbTrans = db.Database.BeginTransaction())
                {
                    try
                    {
                        DateTime dt = DateTime.Now;
                        user.CreationTime = dt;
                        user.CreationUser = "0";
                        user.Deleted = 0;
                        db.Demo_User.Attach(user);
                        db.Entry(user).State = EntityState.Added;
                        int updateRecord = db.SaveChanges();
                        if (updateRecord != 1)
                        {
                            throw new Exception("保存失败！");
                        }

                        dbTrans.Commit();
                        result.IsSuccess = true;
                        result.Message = "保存成功!";
                    }
                    catch (Exception ex)
                    {
                        dbTrans.Rollback();
                        result.IsSuccess = false;
                        result.Message = ex.Message;
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public CommonOutPutVm SaveEditUserInfo(Demo_User user)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                using (var dbTrans = db.Database.BeginTransaction())
                {
                    try
                    {
                        DateTime dt = DateTime.Now;
                        Demo_User item = db.Demo_User.Where(p => p.Id == user.Id).FirstOrDefault();
                        item.UserName = user.UserName;
                        item.NickName = user.NickName;
                        item.Password = user.Password;
                        item.Status = user.Status;
                        item.LastUpdateTime = dt;
                        item.LastUpdateUser = "0";
                        db.Demo_User.Attach(item);
                        db.Entry(item).State = EntityState.Modified;
                        int updateRecord = db.SaveChanges();
                        if (updateRecord != 1)
                        {
                            throw new Exception("修改失败！");
                        }

                        dbTrans.Commit();
                        result.IsSuccess = true;
                        result.Message = "修改成功!";
                    }
                    catch (Exception ex)
                    {
                        dbTrans.Rollback();
                        result.IsSuccess = false;
                        result.Message = ex.Message;
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="enable"></param>
        /// <returns></returns>
        public List<Demo_User> ExportTable(string userName, int enable)
        {
            using (var db = new RMSEntities())
            {
                var q = db.Demo_User.Where(p => p.Deleted == 0);
                if (!string.IsNullOrEmpty(userName))
                {
                    q = q.Where(p => p.UserName.Contains(userName));
                }
                if (enable >= 0)
                {
                    q = q.Where(p => p.Status == enable);
                }
                var lstUsers = q.OrderBy(p => p.CreationTime).ToList();
                return lstUsers;
            }
        }
        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public CommonOutPutVm ImportExcel(DataTable dt)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                using (var dbTrans = db.Database.BeginTransaction())
                {
                    try
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (string.IsNullOrEmpty(dr[0].ToString()))
                            {
                                break;
                            }
                            Demo_User user = new Demo_User();
                            var UserName = dr[0].ToString();
                            if (string.IsNullOrEmpty(UserName))
                            {
                                throw new Exception("缺少用户名信息");
                            }
                            user.UserName = UserName;
                            var Password = dr[1].ToString();
                            if (string.IsNullOrEmpty(Password))
                            {
                                throw new Exception("缺少密码信息");
                            }
                            user.Password = Password;
                            var NickName = dr[2].ToString();
                            if (string.IsNullOrEmpty(NickName))
                            {
                                throw new Exception("缺少昵称信息");
                            }
                            user.NickName = NickName;
                            var Status = dr[3].ToString();
                            if (string.IsNullOrEmpty(Status))
                            {
                                throw new Exception("缺少状态信息");
                            }
                            if (Status != "0" && Status != "1")
                            {
                                throw new Exception("状态信息错误");
                            }
                            user.Status =int.Parse(Status);
                            
                            DateTime dtime = DateTime.Now;
                            user.CreationTime = dtime;
                            user.CreationUser = "0";
                            user.Deleted = 0;
                            db.Demo_User.Attach(user);
                            db.Entry(user).State = EntityState.Added;
                            int updateRecord = db.SaveChanges();
                            if (updateRecord != 1)
                            {
                                throw new Exception("保存失败！");
                            }
                        }
                        dbTrans.Commit();
                        result.IsSuccess = true;
                    }
                    catch (Exception ex)
                    {
                        dbTrans.Rollback();
                        throw new Exception(ex.Message);
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 根据Id获取未删除的实体
        /// </summary>
        /// <param name="id">Id主键</param>
        /// <returns></returns>
        public Demo_User GetById(string id)
        {
            Demo_User result = new Demo_User();
            using (var db=new RMSEntities())
            {
                result = db.Demo_User.AsNoTracking().FirstOrDefault(p => p.Id == id && p.Deleted == (int)E_Deleted.Normal);
            }
            return result;
        }

        public CommonOutPutVm Delete(string id)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            using (var db=new RMSEntities())
            {
                db.Database.ExecuteSqlCommand("update Demo_User set Deleted=1 where Id in (" + id + ")");
                db.SaveChanges();
            }
            result.IsSuccess = true;
            result.Message = "删除成功!";
            return result;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="start">开始行</param>
        /// <param name="length">单页行数</param>
        /// <param name="orderName">排序字段</param>
        /// <param name="orderType">排序方向</param>
        /// <param name="total">数据总数</param>
        /// <param name="searchValue">搜索框</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public List<Demo_User> GetByPage(PageParams page, string searchValue, E_Status status)
        {
            List<Demo_User> result = new List<Demo_User>();
            using (var db = new RMSEntities())
            {
                var q = db.Demo_User.Where(p => p.Deleted == (int)E_Deleted.Normal);
                #region where
                if (!string.IsNullOrWhiteSpace(searchValue))
                {
                    q = q.Where(p => p.UserName.Contains(searchValue) || p.NickName.Contains(searchValue));
                }
                if (status != E_Status.All)
                {
                    q = q.Where(p => p.Status == (int)status);
                }
                #endregion
                page.Total = q.Count();
                #region order by
                if (string.IsNullOrWhiteSpace(page.Order))
                {
                    q = q.OrderBy(p => p.CreationTime);
                }
                else
                {
                    var orderExpression = string.Format("{0} {1}", page.Order, page.OrderType);
                    q = q.OrderBy(orderExpression);
                }
                #endregion
                q = q.Skip(page.Start).Take(page.Length);
                result = q.ToList();
            }
            return result;
        }
    }
}
